package com.owen.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owen.pojo.Fenlei;
import com.owen.pojo.Product;
import com.owen.pojo.Supplier;
import com.owen.server.SupplierServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/supplier")
public class SupplierController {

    @Autowired
    private SupplierServer supplierServer;
    private Optional<Object> byProduct;

    @ResponseBody
    @RequestMapping(value = "/fileExport")
    public void fileExport(Supplier supplier, HttpServletResponse response) throws ClassNotFoundException, IndexOutOfBoundsException, IOException {
        // 生成excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 数据库查询
        List<Supplier> suppliers = supplierServer.findByName(supplier);
        List<Map<String, Object>> rows = suppliers.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId() == null ? "" : item.getId().toString());
            maps.put("createTime", item.getCreateTime() == null ? "" : item.getCreateTime().toString());
            maps.put("name", item.getName());
            maps.put("supplierName", item.getSupplierName());
            maps.put("product", item.getProduct());
            maps.put("address", item.getAddress());
            maps.put("addressPhoto", item.getAddressPhoto());
            maps.put("details", item.getDetails());
            return maps;
        }).collect(Collectors.toList());

        // Title
        int columns = Class.forName("com.owen.pojo.Supplier").getDeclaredFields().length;
        writer.merge(columns - 1, "供应商信息");
        // Header
        writer.addHeaderAlias("id", "主键ID");
        writer.addHeaderAlias("createTime", "注册日期");
        writer.addHeaderAlias("name", "工厂负责人姓名");
        writer.addHeaderAlias("supplierName", "厂名");
        writer.addHeaderAlias("product", "主要产品");
        writer.addHeaderAlias("address", "厂址");
        writer.addHeaderAlias("addressPhoto", "厂址周围照片");
        writer.addHeaderAlias("details", "详情");

        // Body
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 30);
        writer.setColumnWidth(5, 30);
        writer.setColumnWidth(6, 30);
        writer.setColumnWidth(7, 30);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("供应商信息-" + DateUtil.today() + ".xls", "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @ResponseBody
    @RequestMapping(value = "/findAll")
    public String findAll() {

        PageHelper.startPage(1, 10);
        List<Supplier> suppliers = supplierServer.findAll();
        PageInfo<Supplier> supplierInfo = new PageInfo<>(suppliers);

        Map<String, Object> res = new HashMap<>();
        if (suppliers != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", supplierInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/findByName")
    public String findByName(Supplier supplier, Integer xuanzhepage, String currentPage) {

        // 获取页数
        Integer current = 1;
        if (currentPage != null) {
            current = Integer.valueOf(currentPage);
        }

        PageHelper.startPage(current, xuanzhepage);
        List<Supplier> suppliers = supplierServer.findByName(supplier);
        PageInfo<Supplier> supplierInfo = new PageInfo<>(suppliers);

        Map<String, Object> res = new HashMap<>();
        if (suppliers != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", supplierInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }


    @ResponseBody
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(Integer [] ids) {
        Map<String,Object> res = new HashMap<>();
        Integer count = supplierServer.deleteBatch(ids);
        if (count > 0) {
            res.put("code", 200);
            res.put("msg", "删除成功！");
        }else {
            res.put("code", 201);
            res.put("msg", "删除失败！");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/findById/{id}")
    public String findById(@PathVariable("id") Integer id) {
        Supplier supplcier = supplierServer.findById(id);
        Map<String, Object> res = new HashMap<>();
        if (supplcier != null) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", supplcier);
        } else {
            res.put("code", "201");
            res.put("msg", "查询失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        Integer count = supplierServer.deleteById(id);
        Map<String, Object> res = new HashMap<>();
        if (count > 0) {
            res.put("code", "200");
            res.put("msg", "删除成功");
        } else {
            res.put("code", "201");
            res.put("msg", "删除失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(Supplier supplier, HttpSession session, @RequestParam("sAddressPhoto") MultipartFile file) throws IOException {
        String concat = "supplierPicture";
        String uploadPath = session.getServletContext().getRealPath(concat);

        // 上传文件的名字
        String uploadFileName = file.getOriginalFilename();
        // 后缀名
        String hzm = uploadFileName.substring(uploadFileName.lastIndexOf("."));
        // 上传文件名字
        String fileName = System.currentTimeMillis() + hzm;

        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(uploadPath + File.separator + fileName));

        supplier.setAddressPhoto(File.separator + concat + File.separator + fileName);
        supplierServer.addSupplier(supplier);
        return "supplier/supplierlist";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Supplier supplier, HttpSession session, @RequestParam("sAddressPhoto") MultipartFile file) throws IOException {
        if (file.getSize() > 0) {
            String concat = "supplierPicture";
            String uploadPath = session.getServletContext().getRealPath(concat);

            // 上传文件的名字
            String uploadFileName = file.getOriginalFilename();
            // 后缀名
            String hzm = uploadFileName.substring(uploadFileName.lastIndexOf("."));
            // 上传文件名字
            String fileName = System.currentTimeMillis() + hzm;

            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(uploadPath + File.separator + fileName));

            supplier.setAddressPhoto(File.separator + concat + File.separator + fileName);
        }
        supplierServer.updateById(supplier);
        return "supplier/supplierlist";
    }

}
